<?php

namespace App\Http\Controllers\group;

use App\Constant\Enum;
use App\Http\Controllers\api\BaseController;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserWalletActive;
use App\Models\UserWithdraw;
use Symfony\Component\HttpFoundation\Response as HttpResponse;

class AuthController extends BaseController
{
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['phone', 'password']);

        if (empty($credentials)) {
            return $this->error('账号密码为空！');
        }
        if (!$token = auth('jwt')->attempt($credentials)) {
            return $this->error('账户信息不正确');
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userinfo()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $userinfo = $this->getUserInfo($user);

        return $this->success($userinfo->toArray());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return $this->success('成功退出');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        $user = auth('jwt')->setToken($token)->user();
        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('jwt')->factory()->getTTL() * 60,
            'user' => $this->getUserInfo($user),
        ]);
    }

    private function getUserInfo(User $user)
    {
        $exchangeRate = Setting::get('exchange_rate');
        // 可提现金额
        $wallet = $user->wallet()->first();
        $withdrawable = sprintf("%.2f", (max(($wallet->commission_coins ?? 0), 0) - $wallet->locked_coins) / $exchangeRate);

        // 已提现金额
        $coins = UserWalletActive::query()
            ->where([
                'user_id' => $user->getAttribute('id'),
                'wallet_type' => Enum::WALLET_TYPE_COMMISSION,
                'action' => Enum::WALLET_ACTIVE_ACTION_OUTCOME,
                'status' => Enum::ADREWARD_DETAIL_COLLECT_STATUS_APPROVED,
            ])
            ->sum('coins');

        // 待审核金额
        $pending = UserWithdraw::query()
            ->where([
                'user_id' => $user->getAttribute('id'),
                'status' => Enum::TRANSACTION_STATUS_PENDING,
                'wallet_type' => Enum::WALLET_TYPE_COMMISSION,
            ])
            ->sum('money');


        $outcomes = sprintf("%.2f", $coins / $exchangeRate);
        $user->bank = [
            'withdrawable' => $withdrawable,
            'pending' => $pending,
            'outcomes' => $outcomes,
        ];
        return $user;
    }
}
